from PyQt4 import QtCore
from paramiko import Transport, Channel
from buffers import Buffers
import time
#import socket
import socks

class ConexaoSSH(QtCore.QThread):
    def __init__(self, config, saidassh, arquivo):
        QtCore.QThread.__init__(self)
        self.config = config
        self.conectado = False
        self.saidassh = saidassh
        self.arquivo = arquivo

    def setconfig(self,config):
        self.config = config

    def conectar(self):
        if not self.conectado:
            self.start()
        else:
            self.conexao(True)
        
    def desconectar(self):
        self.conectado = False
        self.chann.close()
        self.transport.close()
        self.sock.close()

    def conexao(self, state,error=None):
        self.conectado = state
        if state == True:
            self.emit(QtCore.SIGNAL("connectsuccess()"))
        else:
            self.emit(QtCore.SIGNAL("connectfailed(PyQt_PyObject)"),error)
            
    def enviaShell(self,comando):
        self.chann.exec_command(comando)
    
    def enviaComando(self,comando):
        comando = comando + '\n'
        if self.conectado:
            self.chann.send(comando)
        else:
            raise Exception('Falha no envio ssh')

    def run(self):
        try:
            self.sock = socks.socksocket()
            if self.config.use_proxy == '1':
                self.sock.setproxy(int(self.config.proxytype), self.config.proxyaddr, int(self.config.proxyport), False, self.config.proxylogin, self.config.proxysenha)
            self.sock.settimeout(10)
            self.sock.connect((self.config.ssh_ip,int(self.config.ssh_porta)))
            self.transport = Transport(self.sock)
            self.transport.set_keepalive(60)
            self.transport.connect(username=self.config.ssh_login, password=self.config.ssh_senha)
            self.chann = self.transport.open_session()
            self.chann.get_pty()
            self.bufferssh = Buffers(self.saidassh, self.chann.recv, self.arquivo, self.chann.recv_ready, 0.1)
            self.conexao(True)
        except (Exception), e:
            self.conexao(False, e)
            print 'Nao conectou devido a:'
            print e
